package cn.wildfirechat.app;

import cn.wildfirechat.app.model.GoogleUser;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdTokenVerifier;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

@Service
@Slf4j
public class GoogleAuthService {
    private static final Logger LOG = LoggerFactory.getLogger(GoogleAuthService.class);
    
    // 你的Google OAuth 2.0 客户端ID
    @Value("${google.oauth.client-id}")
    private String googleClientId;
    
    private GoogleIdTokenVerifier verifier;
    
    @PostConstruct
    public void init() {
        NetHttpTransport transport = new NetHttpTransport();
        JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
        
        verifier = new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
                .setAudience(Collections.singletonList(googleClientId))
                .build();
    }
    
    /**
     * 验证Google ID Token
     * @param idTokenString 从前端传来的Google ID Token
     * @return GoogleUser 如果验证成功，返回用户信息；否则返回null
     */
    public GoogleUser verifyIdToken(String idTokenString) {
        try {
            GoogleIdToken idToken = verifier.verify(idTokenString);
            if (idToken != null) {
                GoogleIdToken.Payload payload = idToken.getPayload();
                
                String userId = payload.getSubject();
                String email = payload.getEmail();
                boolean emailVerified = payload.getEmailVerified();
                String name = (String) payload.get("name");
                String pictureUrl = (String) payload.get("picture");
                
                if (!emailVerified) {
                    LOG.warn("Google account email not verified: {}", email);
                    return null;
                }
                
                return new GoogleUser(userId, email, name, pictureUrl);
            } else {
                LOG.error("Invalid Google ID token");
                return null;
            }
        } catch (GeneralSecurityException | IOException e) {
            LOG.error("Failed to verify Google ID token", e);
            return null;
        }
    }
}